import { getPlatformInfo, getDeviceId } from './oauth'
import { useUserStore } from '@/store/user'

// 重新导出常用功能
export { getPlatformInfo, getDeviceId } from './oauth'

/**
 * 格式化时间
 */
export const formatTime = (
  time: string | number | Date,
  format: string = 'YYYY-MM-DD HH:mm:ss'
): string => {
  const date = new Date(time)

  const formatMap: Record<string, string> = {
    'YYYY': date.getFullYear().toString(),
    'MM': (date.getMonth() + 1).toString().padStart(2, '0'),
    'DD': date.getDate().toString().padStart(2, '0'),
    'HH': date.getHours().toString().padStart(2, '0'),
    'mm': date.getMinutes().toString().padStart(2, '0'),
    'ss': date.getSeconds().toString().padStart(2, '0')
  }

  let result = format
  Object.keys(formatMap).forEach(key => {
    result = result.replace(key, formatMap[key])
  })

  return result
}

/**
 * 相对时间格式化
 */
export const formatRelativeTime = (time: string | number | Date): string => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day

  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else {
    return formatTime(time, 'YYYY-MM-DD')
  }
}

/**
 * 防抖函数
 */
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: number | undefined

  return (...args: Parameters<T>) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => func(...args), wait) as any
  }
}

/**
 * 节流函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let lastTime = 0

  return (...args: Parameters<T>) => {
    const now = Date.now()
    if (now - lastTime >= wait) {
      lastTime = now
      func(...args)
    }
  }
}

/**
 * 深拷贝
 */
export const deepClone = <T>(obj: T): T => {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any
  }

  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as any
  }

  if (typeof obj === 'object') {
    const cloned: any = {}
    Object.keys(obj).forEach(key => {
      cloned[key] = deepClone((obj as any)[key])
    })
    return cloned
  }

  return obj
}

/**
 * 生成UUID
 */
export const generateUUID = (): string => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

/**
 * 检查是否为空
 */
export const isEmpty = (value: any): boolean => {
  if (value === null || value === undefined) {
    return true
  }

  if (typeof value === 'string') {
    return value.trim() === ''
  }

  if (Array.isArray(value)) {
    return value.length === 0
  }

  if (typeof value === 'object') {
    return Object.keys(value).length === 0
  }

  return false
}

/**
 * 验证邮箱格式
 */
export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 验证手机号格式
 */
export const validatePhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

/**
 * 验证URL格式
 */
export const validateURL = (url: string): boolean => {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

/**
 * 获取URL域名
 */
export const getDomainFromURL = (url: string): string => {
  try {
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'http://' + url
    }
    const urlObj = new URL(url)
    return urlObj.hostname
  } catch {
    return url
  }
}

/**
 * 获取文件图标
 */
export const getFileIcon = (filename: string): string => {
  const ext = filename.split('.').pop()?.toLowerCase()

  const iconMap: Record<string, string> = {
    'pdf': '📄',
    'doc': '📝',
    'docx': '📝',
    'xls': '📊',
    'xlsx': '📊',
    'ppt': '📽️',
    'pptx': '📽️',
    'txt': '📄',
    'jpg': '🖼️',
    'jpeg': '🖼️',
    'png': '🖼️',
    'gif': '🖼️',
    'mp4': '🎥',
    'mp3': '🎵',
    'zip': '📦',
    'rar': '📦'
  }

  return iconMap[ext || ''] || '📄'
}

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'

  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 颜色工具
 */
export const colorUtils = {
  // 十六进制转RGB
  hexToRgb: (hex: string): { r: number; g: number; b: number } | null => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  },

  // RGB转十六进制
  rgbToHex: (r: number, g: number, b: number): string => {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
  },

  // 生成随机颜色
  randomColor: (): string => {
    const colors = [
      '#1890ff', '#52c41a', '#faad14', '#f5222d',
      '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16'
    ]
    return colors[Math.floor(Math.random() * colors.length)]
  }
}

/**
 * 设备信息获取
 */
export const getDeviceInfo = () => {
  const systemInfo = uni.getSystemInfoSync()
  const platformInfo = getPlatformInfo()

  return {
    deviceId: getDeviceId(),
    platform: platformInfo.platform,
    appVersion: '1.0.0', // 从配置中获取
    ...systemInfo
  }
}

/**
 * 自动登录检查
 */
export const autoLogin = async () => {
  const userStore = useUserStore()
  const token = uni.getStorageSync('token')

  if (token && !userStore.isLoggedIn) {
    try {
      await userStore.refreshToken()
      return true
    } catch (error) {
      uni.removeStorageSync('token')
      return false
    }
  }

  return false
}

/**
 * 错误处理
 */
export const handleError = (error: any, defaultMessage: string = '操作失败') => {
  console.error('错误:', error)

  let message = defaultMessage

  if (error?.message) {
    message = error.message
  } else if (typeof error === 'string') {
    message = error
  }

  uni.showToast({
    title: message,
    icon: 'error',
    duration: 2000
  })
}

/**
 * 成功提示
 */
export const showSuccess = (message: string) => {
  uni.showToast({
    title: message,
    icon: 'success',
    duration: 1500
  })
}

/**
 * 加载提示
 */
export const showLoading = (title: string = '加载中...') => {
  uni.showLoading({
    title,
    mask: true
  })
}

/**
 * 隐藏加载
 */
export const hideLoading = () => {
  uni.hideLoading()
}

/**
 * 确认对话框
 */
export const showConfirm = (
  title: string,
  content: string = ''
): Promise<boolean> => {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

/**
 * 页面跳转封装
 */
export const navigateTo = (url: string, params?: Record<string, any>) => {
  let fullUrl = url

  if (params) {
    const query = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    fullUrl += (url.includes('?') ? '&' : '?') + query
  }

  uni.navigateTo({ url: fullUrl })
}

export const redirectTo = (url: string, params?: Record<string, any>) => {
  let fullUrl = url

  if (params) {
    const query = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    fullUrl += (url.includes('?') ? '&' : '?') + query
  }

  uni.redirectTo({ url: fullUrl })
}

export const reLaunch = (url: string, params?: Record<string, any>) => {
  let fullUrl = url

  if (params) {
    const query = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    fullUrl += (url.includes('?') ? '&' : '?') + query
  }

  uni.reLaunch({ url: fullUrl })
}